package com.dminvoicemanager.reports;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceNew;
import com.dminvoicemanager.DM_Reports_Generator;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_Customer_Last_Three_Visit extends Activity {

	SQLiteDatabase mydb;
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	private String LASTTHREE_SUM = "LastThreeSum";

	String item_rec_date_1 = "00/00/0000", item_rec_date_2 = "00/00/0000",
			item_rec_date_3 = "00/00/0000";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", item_result_8 = "0", item_result_9 = "0",
			item_result_10 = "0", item_result_11 = "0", item_result_12 = "0";
	String item_sum_chkid, item_sum_code, item_sum_chk_1, item_sum_chk_2,
			item_sum_chk_3, item_sum_chk_4, item_sum_chk_5, item_sum_chk_6,
			item_sum_chk_7, item_sum_chk_8, item_sum_chk_9, caseQtyStr;
	String SalesType,refInvitemCaseQty;
	int loopprint = 0;
	int day1CS = 0, day2CS = 0, day3CS = 0, sumCSTot = 0;
	int day1PS = 0, day2PS = 0, day3PS = 0, sumPSTot = 0;
	int caseQty = 0;
	double day1Val = 0.0, day2Val = 0.0, day3Val = 0.0, SumValTot = 0.0;

	String currentReportNameSum, currentReportName, invcuscode;
	TextView daterecord_1, daterecord_2, daterecord_3;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");

	public void btnExitScreen(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceNew.class);
		myIntent.putExtra("TAGID", "5");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_customer_last_three_visit);
		Bundle bundle = getIntent().getExtras();
		currentReportNameSum = bundle.getString("REPORTNAME");
		String[] reportdetail = currentReportNameSum.split("/");
		currentReportName = reportdetail[0]; // invcuscode
		invcuscode = reportdetail[1]; // invcusname
		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Last Three Visit Information");

		TextView dmreportfromdate = (TextView) findViewById(R.id.dmreportfromdate);
		dmreportfromdate.setText(getCurrentTimeString().toString());

		daterecord_1 = (TextView) findViewById(R.id.daterecord_1);
		daterecord_2 = (TextView) findViewById(R.id.daterecord_2);
		daterecord_3 = (TextView) findViewById(R.id.daterecord_3);

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("DROP TABLE IF EXISTS LastThreeSum");
		try {
			mydb.execSQL("create table if not exists "
					+ LASTTHREE_SUM
					+ "(lastthreesum_id integer primary key autoincrement,ItemCode text not null,ItemName text not null,Cases_a text not null,Pieces_a text not null,Amount_a text not null,Cases_b text not null,Pieces_b text not null,Amount_b text not null,Cases_c text not null,Pieces_c text not null,Amount_c text not null,SalesType text not null,refInvitemCaseQty text not null);");
		} catch (Exception e) {
		}

		getLastThreeInvDates();
		// viewLastThreeInvoiceSummary();
	}

	private void getLastThreeInvDates() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkLastThreeRec = null;
		try {
			String query = "SELECT recordDate from frepInvoiceSumery Where invoiceComplete != '0' AND InvoiceCustomerCode = '"
					+ invcuscode
					+ "' group by recordDate ORDER BY remprepinv_id DESC LIMIT 3";
			chkLastThreeRec = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (chkLastThreeRec != null) {
			if (chkLastThreeRec.getCount() > 0) {
				while (chkLastThreeRec.moveToNext()) {
					loopprint = loopprint + 1;
					if (loopprint == 1) {
						item_rec_date_1 = chkLastThreeRec.getString(0); // rec_1
																		// date
						Log.v(TAG, "RES 1:" + item_rec_date_1);
					} else if (loopprint == 2) {
						item_rec_date_2 = chkLastThreeRec.getString(0); // rec_1
																		// date
						Log.v(TAG, "RES 2:" + item_rec_date_2);
					} else if (loopprint == 3) {
						item_rec_date_3 = chkLastThreeRec.getString(0); // rec_1
																		// date
						Log.v(TAG, "RES 3:" + item_rec_date_3);
					}
				}
				Log.v(TAG, "Final RES :" + item_rec_date_1 + "|"
						+ item_rec_date_2 + "|" + item_rec_date_3);
				daterecord_1.setText(item_rec_date_1);
				daterecord_2.setText(item_rec_date_2);
				daterecord_3.setText(item_rec_date_3);
				viewLastThreeInvoiceSummary();
			}
		}
	}

	private void viewLastThreeInvoiceSummary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		try {
			String query = "SELECT IH.RefNo,IH.TxnDate,IH.DebCode,ID.Itemcode,ID.CaseQty,ID.Qty,ID.Amt,ID.itemDescription,INS.invoiceRef,INS.invoiceComplete,ID.Type,ID.refInvitemCaseQty FROM FinvHed IH INNER JOIN FinvDet ID ON ID.RefNo = IH.RefNo INNER JOIN frepInvoiceSumery INS ON INS.invoiceRef = IH.RefNo Where IH.DebCode = '"
					+ invcuscode + "' AND INS.invoiceComplete = '2'";

			allrowitemsdes = mydb.rawQuery(query, null);
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {

					while (allrowitemsdes.moveToNext()) {
						resetValues();

						// loopprint = loopprint + 1;
						item_result_1 = allrowitemsdes.getString(7); // itemDescription
						item_result_2 = allrowitemsdes.getString(1); // TxnDate
						item_result_3 = allrowitemsdes.getString(3); // Item
						Log.v(TAG, "DATE COM|" + item_result_2 + "|"
								+ item_rec_date_1 + "|"); // code
						if (item_result_2.equals(item_rec_date_1)) {
							item_result_4 = allrowitemsdes.getString(4); // CaseQty
							item_result_5 = allrowitemsdes.getString(5); // Total PiceQty
							item_result_6 = allrowitemsdes.getString(6); // Amount
						} else if (item_result_2.equals(item_rec_date_2)) {
							item_result_7 = allrowitemsdes.getString(4); // CaseQty
							item_result_8 = allrowitemsdes.getString(5); // Total PiceQty
							item_result_9 = allrowitemsdes.getString(6); // Amount
						} else if (item_result_2.equals(item_rec_date_3)) {
							item_result_10 = allrowitemsdes.getString(4); // CaseQty
							item_result_11 = allrowitemsdes.getString(5); // Total PiceQty
							item_result_12 = allrowitemsdes.getString(6); // Amount
						}
						SalesType  = allrowitemsdes.getString(10); // SalesType
						refInvitemCaseQty  = allrowitemsdes.getString(11); // CaseQty
						insertNewSumRecord();
					}
				}
			}
			allrowitemsdes.close();
			mydb.close();
			DisplayLastThreeInvoiceSum();

		} catch (Exception e) {
		}
	}

	private void DisplayLastThreeInvoiceSum() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		ListView lvtypedes = (ListView) findViewById(R.id.dnlastthreeinvoicelist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4", "item_result_5",
				"item_result_6", "item_result_7", "item_result_8",
				"item_result_9", "item_result_10", "item_result_11",
				"item_result_12", "item_result_13" };

		int[] totrdes = new int[] { R.id.item_name, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5,
				R.id.record_6, R.id.record_7, R.id.record_8, R.id.record_9,
				R.id.record_10, R.id.record_11, R.id.record_12 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		Cursor allrowchksum = null;
		try {
			String queryChkSum = "SELECT ItemName,sum(case when ItemCode != 99 then Cases_a else 0 end),sum(case when ItemCode != 99 then Pieces_a else 0 end),sum(case when ItemCode != 99 then Amount_a else 0 end),sum(case when ItemCode != 99 then Cases_b else 0 end),sum(case when ItemCode != 99 then Pieces_b else 0 end),sum(case when ItemCode != 99 then Amount_b else 0 end),sum(case when ItemCode != 99 then Cases_c else 0 end),sum(case when ItemCode != 99 then Pieces_c else 0 end),sum(case when ItemCode != 99 then Amount_c else 0 end),SalesType,refInvitemCaseQty from LastThreeSum group by ItemCode";
			allrowchksum = mydb.rawQuery(queryChkSum, null);
		} catch (Exception e) {
		}
		if (allrowchksum != null) {
			if (allrowchksum.getCount() > 0) {
				while (allrowchksum.moveToNext()) {
					int lineCS = 0, lineCSday1 = 0, lineCSday2 = 0, lineCSday3 = 0;
					int linePS = 0, linePSday1 = 0, linePSday2 = 0, linePSday3 = 0;
					double lineValue = 0.0, lineValueday1 = 0.0, lineValueday2 = 0.0, lineValueday3 = 0.0;
					caseQtyStr = allrowchksum.getString(11);
					caseQty = Integer.parseInt(caseQtyStr);
					
					item_sum_code = allrowchksum.getString(0);
					// day1 - Cases
					item_sum_chk_1 = allrowchksum.getString(1);
					lineCSday1 = Integer.parseInt(item_sum_chk_1);
					//day1CS = day1CS + lineCSday1;
					// day1 - Pieces
					item_sum_chk_2 = allrowchksum.getString(2);
					linePSday1 = Integer.parseInt(item_sum_chk_2);
					if(caseQty < linePSday1){
						lineCSday1 = linePSday1 / caseQty;
						day1CS = day1CS + lineCSday1;
						linePSday1 = linePSday1 - (lineCSday1 * caseQty);
					}
					else{
						lineCSday1 = 0;
						day1CS = day1CS + lineCSday1;
					}
					day1PS = day1PS + linePSday1;
					// day1 - Value
					item_sum_chk_3 = allrowchksum.getString(3);
					lineValueday1 = Double.parseDouble(item_sum_chk_3);
					day1Val = day1Val + lineValueday1;

					// day2 - Cases
					item_sum_chk_4 = allrowchksum.getString(4);
					lineCSday2 = Integer.parseInt(item_sum_chk_4);
					//day2CS = day2CS + lineCSday2;
					// day2 - Pieces
					item_sum_chk_5 = allrowchksum.getString(5);
					linePSday2 = Integer.parseInt(item_sum_chk_5);
					if(caseQty < linePSday2){
						lineCSday2 = linePSday2 / caseQty;
						day2CS = day2CS + lineCSday2;
						linePSday2 = linePSday2 - (lineCSday2 * caseQty);
					}
					else{
						lineCSday2 = 0;
						day2CS = day2CS + lineCSday2;
					}
					day2PS = day2PS + linePSday2;
					// day2 - Value
					item_sum_chk_6 = allrowchksum.getString(6);
					lineValueday2 = Double.parseDouble(item_sum_chk_6);
					day2Val = day2Val + lineValueday2;

					// day3 - Cases
					item_sum_chk_7 = allrowchksum.getString(7);
					lineCSday3 = Integer.parseInt(item_sum_chk_7);
					//day3CS = day3CS + lineCSday3;
					
					// day3 - Pieces
					item_sum_chk_8 = allrowchksum.getString(8);
					linePSday3 = Integer.parseInt(item_sum_chk_8);
					if(caseQty < linePSday3){
						lineCSday3 = linePSday3 / caseQty;
						day3CS = day3CS + lineCSday3;
						linePSday3 = linePSday3 - (lineCSday3 * caseQty);
					}
					else{
						lineCSday3 = 0;
						day3CS = day3CS + lineCSday3;
					}
					day3PS = day3PS + linePSday3;
					linePS = linePSday1 + linePSday2 + linePSday3;
					// day3 - Value
					item_sum_chk_9 = allrowchksum.getString(9);
					lineValueday3 = Double.parseDouble(item_sum_chk_9);
					
					lineCS = lineCSday1 + lineCSday2 + lineCSday3;
					day3Val = day3Val + lineValueday3;
					lineValue = lineValueday1 + lineValueday2 + lineValueday3;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("item_result_1", item_sum_code);
					maptrdes.put("item_result_2", "" + lineCSday1);
					maptrdes.put("item_result_3", "" + linePSday1);
					maptrdes.put("item_result_4", item_sum_chk_3);
					maptrdes.put("item_result_5", "" + lineCSday2);
					maptrdes.put("item_result_6", "" + linePSday2);
					maptrdes.put("item_result_7", item_sum_chk_6);
					maptrdes.put("item_result_8", "" + lineCSday3);
					maptrdes.put("item_result_9", "" + linePSday3);
					maptrdes.put("item_result_10", item_sum_chk_9);

					String lineTotCS = Integer.toString(lineCS);
					String lineTotPS = Integer.toString(linePS);
					String lineTotVal = formatValues.format(lineValue);
					maptrdes.put("item_result_11", lineTotCS);
					maptrdes.put("item_result_12", lineTotPS);
					maptrdes.put("item_result_13", lineTotVal);

					sumCSTot = sumCSTot + lineCS;
					sumPSTot = sumPSTot + linePS;
					SumValTot = SumValTot + lineValue;
					// fill in the grid_item layout
					fillMapstrdes.add(maptrdes);
					SimpleAdapter adaptertrdes = new SimpleAdapter(this,
							fillMapstrdes,
							R.layout.dm_customer_last_three_visit_raw,
							fromtrdes, totrdes);
					lvtypedes.setAdapter(adaptertrdes);
				}
			}
		}

		HashMap<String, String> maptrdes = new HashMap<String, String>();
		maptrdes.put("item_result_1", "Total Values");
		String day1CSStr = Integer.toString(day1CS);
		maptrdes.put("item_result_2", day1CSStr);
		String day1PSStr = Integer.toString(day1PS);
		maptrdes.put("item_result_3", day1PSStr);
		String day1ValStr = formatValues.format(day1Val);
		maptrdes.put("item_result_4", day1ValStr);

		String day2CSStr = Integer.toString(day2CS);
		maptrdes.put("item_result_5", day2CSStr);
		String day2PSStr = Integer.toString(day2PS);
		maptrdes.put("item_result_6", day2PSStr);
		String day2ValStr = formatValues.format(day2Val);
		maptrdes.put("item_result_7", day2ValStr);

		String day3CSStr = Integer.toString(day3CS);
		maptrdes.put("item_result_8", day3CSStr);
		String day3PSStr = Integer.toString(day3PS);
		maptrdes.put("item_result_9", day3PSStr);
		String day3ValStr = formatValues.format(day3Val);
		maptrdes.put("item_result_10", day3ValStr);

		String sumCSTotStr = Integer.toString(sumCSTot);
		maptrdes.put("item_result_11", sumCSTotStr);
		String sumPSTotStr = Integer.toString(sumPSTot);
		maptrdes.put("item_result_12", sumPSTotStr);
		String SumValTotStr = formatValues.format(SumValTot);
		maptrdes.put("item_result_13", SumValTotStr);

		// fill in the grid_item layout
		fillMapstrdes.add(maptrdes);
		SimpleAdapter adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
				R.layout.dm_customer_last_three_visit_raw, fromtrdes, totrdes);
		lvtypedes.setAdapter(adaptertrdes);
	}

	private void resetValues() {
		// TODO Auto-generated method stub
		item_result_1 = "0";
		item_result_2 = "0";
		item_result_3 = "0";
		item_result_4 = "0";
		item_result_5 = "0";
		item_result_6 = "0";
		item_result_7 = "0";
		item_result_8 = "0";
		item_result_9 = "0";
		item_result_10 = "0";
		item_result_11 = "0";
		item_result_12 = "0";
	}

	private void insertNewSumRecord() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addItemsLthreeSum = new ContentValues();
			addItemsLthreeSum.put("ItemCode", item_result_3);
			addItemsLthreeSum.put("ItemName", item_result_1);
			
			if(SalesType.equals("SA") || SalesType.equals("FI")){
				// daterecord_1
				// if (item_result_2.equals(daterecord_1)) {
				addItemsLthreeSum.put("Cases_a", item_result_4);
				addItemsLthreeSum.put("Pieces_a", item_result_5);
				addItemsLthreeSum.put("Amount_a", item_result_6);
				// }

				// daterecord_2
				// if (item_result_2.equals(daterecord_2)) {
				addItemsLthreeSum.put("Cases_b", item_result_7);
				addItemsLthreeSum.put("Pieces_b", item_result_8);
				addItemsLthreeSum.put("Amount_b", item_result_9);
				// }
				// daterecord_3
				// if (item_result_2.equals(daterecord_3)) {
				addItemsLthreeSum.put("Cases_c", item_result_10);
				addItemsLthreeSum.put("Pieces_c", item_result_11);
				addItemsLthreeSum.put("Amount_c", item_result_12);
				// }
			}
			else{
				// daterecord_1
				// if (item_result_2.equals(daterecord_1)) {
				addItemsLthreeSum.put("Cases_a", item_result_4);
				addItemsLthreeSum.put("Pieces_a", "-"+item_result_5);
				addItemsLthreeSum.put("Amount_a", item_result_6);
				// }

				// daterecord_2
				// if (item_result_2.equals(daterecord_2)) {
				addItemsLthreeSum.put("Cases_b", item_result_7);
				addItemsLthreeSum.put("Pieces_b", "-"+item_result_8);
				addItemsLthreeSum.put("Amount_b", item_result_9);
				// }
				// daterecord_3
				// if (item_result_2.equals(daterecord_3)) {
				addItemsLthreeSum.put("Cases_c", item_result_10);
				addItemsLthreeSum.put("Pieces_c", "-"+item_result_11);
				addItemsLthreeSum.put("Amount_c", item_result_12);
				// }
			}
			addItemsLthreeSum.put("SalesType", SalesType);
			addItemsLthreeSum.put("refInvitemCaseQty", refInvitemCaseQty);
			
			mydb.insert(LASTTHREE_SUM, null, addItemsLthreeSum);
		} catch (Exception e) {
		}
		mydb.close();
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
